<template>
  <div class="w-full max-w-[567px] mx-auto backdrop-blur-[40px]">
    <!-- 搜索图标 -->
    <div class="absolute left-3 top-3 text-blue-500">
      <section
        class="flex items-center justify-center overflow-hidden bg-cover h-[24px] w-[24px] rounded-[6px]"
        :style="{ backgroundImage: `url(${baiduLogo})` }"
      ></section>
    </div>

    <!-- 搜索输入框 -->
    <input
      v-model="searchQuery"
      @input="debouncedSearch"
      @focus="showSuggestions = true"
      @blur="hideSuggestionsDelayed"
      @keydown.down.prevent="navigateSuggestion(1)"
      @keydown.up.prevent="navigateSuggestion(-1)"
      @keydown.enter="submitSearch"
      type="text"
      :placeholder="$t('message.searchPlaceholder')"
      class="w-full h-12 pl-12 pr-4 py-2 rounded-xl border bg-color-opacity focus:outline-none focus:bg-color-focus"
    />

    <!-- 关闭按钮 -->
    <button
      v-show="searchQuery"
      @click="clearSearch"
      class="absolute right-3 top-[14px] text-gray-400 hover:text-gray-600"
    >
      <svg
        xmlns="http://www.w3.org/2000/svg"
        class="h-5 w-5"
        viewBox="0 0 20 20"
        fill="currentColor"
      >
        <path
          fill-rule="evenodd"
          d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
          clip-rule="evenodd"
        />
      </svg>
    </button>

    <!-- 搜索建议列表 -->
    <ul
      v-show="showSuggestions && suggestions.length"
      class="absolute w-full bg-white mt-1 rounded-md shadow-lg border border-gray-200 z-searchList"
    >
      <li
        v-for="(suggestion, index) in suggestions"
        :key="index"
        @mousedown="selectSuggestion(suggestion)"
        :class="[
          'px-4 py-2 hover:bg-gray-100 cursor-pointer',
          { 'bg-gray-100': index === selectedIndex },
        ]"
      >
        <div class="flex items-center">
          <span
            class="iconfont icon-magnifier_icon h-5 w-5 mr-2 text-gray-400"
          ></span>
          {{ suggestion }}
        </div>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { debounce } from '../utils/tools';
import baiduLogo from '../assets/image/baidu-logo.webp';

const searchQuery = ref('');
const suggestions = ref([]);
const showSuggestions = ref(false);
const selectedIndex = ref(-1);

// 使用百度搜索建议API
const fetchSuggestions = (query) => {
  return new Promise((resolve) => {
    const script = document.createElement('script');
    const callbackName =
      'jsonp_' + Date.now() + Math.floor(Math.random() * 100000);

    window[callbackName] = (data) => {
      delete window[callbackName];
      document.body.removeChild(script);
      resolve(data.s);
    };

    script.src = `https://suggestion.baidu.com/su?wd=${encodeURIComponent(
      query
    )}&cb=${callbackName}`;
    document.body.appendChild(script);
  });
};

const debouncedSearch = debounce(async () => {
  if (searchQuery.value) {
    suggestions.value = await fetchSuggestions(searchQuery.value);
    selectedIndex.value = -1; // 重置选中索引
  } else {
    suggestions.value = [];
  }
}, 300);

const selectSuggestion = (suggestion) => {
  searchQuery.value = suggestion;
  performSearch(suggestion);
};

const clearSearch = () => {
  searchQuery.value = '';
  suggestions.value = [];
  selectedIndex.value = -1;
};

const hideSuggestionsDelayed = () => {
  // 忘记为什么要delay了，先注释掉
  // setTimeout(() => {}, 200);

  showSuggestions.value = false;
};

const navigateSuggestion = (direction) => {
  if (suggestions.value.length === 0) return;

  selectedIndex.value += direction;
  if (selectedIndex.value < 0) {
    selectedIndex.value = suggestions.value.length - 1;
  } else if (selectedIndex.value >= suggestions.value.length) {
    selectedIndex.value = 0;
  }

  searchQuery.value = suggestions.value[selectedIndex.value];
};

const submitSearch = () => {
  hideSuggestionsDelayed();
  performSearch(searchQuery.value);
};

const performSearch = (query) => {
  // 打开新页面进行搜索
  window.open(
    `https://www.baidu.com/s?wd=${encodeURIComponent(query)}`,
    '_blank'
  );
};

onMounted(() => {
  // 可以在这里进行一些初始化操作，比如加载历史搜索记录等
});
</script>

<style>
/* 响应式设计 */
@media (max-width: 640px) {
  .max-w-\[567px\] {
    max-width: 90%;
  }
}
</style>
